import urllib.request

# 1.普通请求
# response = urllib.request.urlopen("http://www.baidu.com")
# print(response.read().decode("utf-8"))
# print(response.status)
# print(response.getheaders())
# print(response.getheader("Server"))

# data = bytes(urllib.parse.urlencode({'items':'ww','aaa':'eeee'}), encoding='utf8')
# response2 = urllib.request.urlopen("http:httpbin.org/post", data=data,timeout=1)
# print(response2.read().decode("utf-8"))

# 2.Request参数
# class urllib. request. Request (ur1, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
# dict = {'aa':'bb'}
# data= bytes(parse.urlencode(dict), encoding='utf8 ’)
# headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE S.S; Windows NT)',' Host ': 'httpbin.org'}
# req = request.Request(url='http://www.baidu.com', data=data, headers=headers, method=’ POST’)
from math import e
from urllib.error import URLError

request = urllib.request.Request("http://www.baidu.com")
response3 = urllib.request.urlopen(request, timeout=10)
print(response3.read().decode("utf-8"))

# 3.Handler处理器
# a.HTTBasicAuthHandler 授权验证
# p = urllib.HTTPPasswordMgrWithDefaultRealm()
# p.add_password(None, u r l , username , password)
# auth_handler = urllib.HTTPBasicAuthHandler(p)
# opener = build_opener(auth_handler)

# b.ProxyHandler 代理
# proxy_handler = urllib.ProxyHandler(
#         {'http ': 'htt p : // 1 2 7 . o . o . 1:9743 ',
#          ' https ': ' https://127.0 .0.1:9743 '})
# opener = urllib.build_opener(proxy_handler)
# try:
#     response = opener.open('https://www.baidu.com')
#     print(response.read().decode('utf-8'))
# except URLError as e:
#     print(e.reason)
